fs.mkdir("data/logs/");
var Settings = regSettings('logServer',{
	// Port to run the server on
	port: 9002,
	// How quickly to check if the port is in use
	check_interval: 1000,
	// how many times to check before failing to start
	check_timeout: 10
});
listen(/^.+/i,function(match,data,replyTo,connection){
	var nick;
	if(replyTo===null){
		replyTo = "- server -";
	}else{
		try{
			nick = (/^:([^!]+)!.*PRIVMSG ([^ ]+) :(.+)$/i).exec(data)[1];
			data = (/^:([^!]+)!.*PRIVMSG ([^ ]+) :(.+)$/i).exec(data)[3];
			if(nick == 'OmnomIRC'){
				data = ("\x03\x03").exec(data);
				nick = data[1];
				data = data[2];
			}else{
				replyTo = replyTo.trim().toLowerCase();
			}
		}catch(e){
			disp.error(e);
			replyTo = "- server -";
		}
	}
	var d = new Date();
	var p = "data/logs/"+connection.config.host+" "+connection.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/"+replyTo));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	if(replyTo == "- server -" && (new RegExp("^:(.+) 372 "+connection.config.nick+" :(.+)$")).exec(data) === null){
		l.write("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	"+data+"\r\n");
	}else{
		if(data.indexOf("\x01ACTION ")!=-1){
			l.write("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	*"+nick+"	"+data.substr(data.indexOf("\x01ACTION ")+8,data.length-9)+"\r\n");
		}else{
			l.write("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	<"+nick+">	"+data+"\r\n");
		}
	}
	l.end();
});
listen(/^:([^!]+).*PART ([^ ]+) :$/i,function(match,data,replyTo,connection){
	replyTo = match[2].substr(1).trim().toLowerCase();
	var d = new Date();
	var p = "data/logs/"+connection.config.host+" "+connection.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/#"+replyTo));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	* "+match[1]+" has left the channel\r\n");
});
listen(/^:([^!]+).*JOIN :([^ ]+)$/i,function(match,data,replyTo,connection){
	replyTo = match[2].substr(1).trim().toLowerCase();
	var d = new Date();
	var p = "data/logs/"+connection.config.host+" "+connection.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/#"+replyTo));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	* "+match[1]+" has joined the channel\r\n");
});
reply_listen(function(replyTo,msg,connection){
	if(replyTo===null){
		replyTo = "- server -";
	}else{
		replyTo = replyTo.trim().toLowerCase();
	}
	var d = new Date();
	var p = "data/logs/"+connection.config.host+" "+connection.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/"+replyTo.trim()));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	<"+connection.config.nick+">	"+msg+"\r\n");
});
hook('quit',function(){
	var d = new Date();
	var p = "data/logs/"+this.config.host+" "+this.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/- server -"));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	*Connection Quit*\r\n");
});
hook('reconnect',function(){
	var d = new Date();
	var p = "data/logs/"+this.config.host+" "+this.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/- server -"));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	*Reconnected*\r\n");
});
hook('connect',function(){
	var d = new Date();
	var p = "data/logs/"+this.config.host+" "+this.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/- server -"));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	*Connected*\r\n");
});
hook('timeout',function(){
	var d = new Date();
	var p = "data/logs/"+this.config.host+" "+this.config.port;
	fs.mkdir(p);
	fs.mkdir((p+="/- server -"));
	var l = fs.createWriteStream((p+="/"+d.toDateString()+".log"),{
		flags: 'a',
		encoding: 'ascii'
	});
	l.end("["+d.getHours()+":"+addZero(d.getMinutes())+":"+addZero(d.getSeconds())+"]	*Connection Timeout*\r\n");
});
disp.alert("Starting Log Server");
function addZero(num){
	return (String(num).length < 2) ? num = String("0" + num) :  num = String(num);
}
var count = 0,
	server = http.createServer(function (req, res) {
	function check(d){
		try{
			return fs.statSync(d).isDirectory();
		}catch(er){
			return false;
		}
	}
	var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
	console.log("Serving "+req.url+" to: "+ip);
	if(req.url == '/'){
		res.writeHead(200, {'Content-Type': 'text/html; charset=UTF-8','Server': 'NodeBot/Logs'});
		res.write("<!doctype html>\n<html>\n\t<head>\n\t\t<link rel='icon' type='image/x-icon' href='favicon.ico' />\n\t\t<title>Logs</title>\n\t</head>\n\t<body>");
		var logs = fs.readdirSync('data/logs/');
		if(logs){
			var i,j,f;
			for (i = 0; i < logs.length; i++){
				if(check('data/logs/'+logs[i])){
					var logdirs = fs.readdirSync('data/logs/'+logs[i]);
					if(logdirs){
						res.write('\n\t\t<h1>'+logs[i]+'</h1>\n\t\t<ul>');
						for (j = 0; j < logdirs.length; j++){
							if(
								check('data/logs/'+logs[i]+'/'+logdirs[j])
								&& logdirs[j] != '- server -'
								&& logdirs[j].substr(0,1) == '#'
							){
								var logfiles = fs.readdirSync('data/logs/'+logs[i]+'/'+logdirs[j]);
								if(logfiles){
									logfiles = logfiles.sort(function(a, b) {
										return fs.statSync('data/logs/'+logs[i]+'/'+logdirs[j]+'/'+a).mtime.getTime() - 
											fs.statSync('data/logs/'+logs[i]+'/'+logdirs[j]+'/'+b).mtime.getTime();
									});
									res.write('\n\t\t\t<li>\n\t\t\t\t<h2><a href="?server='+logs[i]+'&channel='+logdirs[j].substr(1,logdirs[j].length-1)+'&date=today">'+logdirs[j]+'</a></h2>\n\t\t\t\t<ul>');
									for (f = 0; f < logfiles.length; f++){
										if(logfiles[f].substr(-4) == '.log'){
											var c = logfiles[f].substr(0,logfiles[f].length-4);
											res.write('\n\t\t\t\t\t<li>\n\t\t\t\t\t\t<a href="?server='+logs[i]+'&channel='+logdirs[j].substr(1,logfiles[f].length-1)+'&date='+c+'">'+c+'</a>\n\t\t\t\t\t</li>');
										}
									}
									res.write('\n\t\t\t\t</ul>\n\t\t\t</li>');
								}
							}
						}
						res.write('\n\t\t</ul>');
					}
				}
			}
		}
		res.end("\n\t</body>\n</html>");
	}else if(req.url == '/favicon.ico'){
		fs.readFile('data/favicon.ico', "binary", function (err,file) {
			if (err) {
				res.writeHead(500, {'Content-Type':'image/x-icon','Server':'NodeBot/Logs'});
				res.write(err+"\n");
				res.end();
				return;
			}
			res.writeHead(200,{'Content-Type':'image/x-icon','Server':'NodeBot/Logs'});
			res.write(file, "binary");
			res.end();
		});
	}else{
		res.writeHead(200, {'Content-Type': 'text/plain;','Server': 'NodeBot/Logs'});
		var log = require('url').parse(req.url,true).query;
		try{
			var n,d = new Date();
			if(log.date == 'today'){
				n = d.toDateString();
			}else{
				n = log.date;
			}
			res.end(fs.readFileSync('data/logs/'+log.server+'/#'+log.channel+'/'+n+'.log','ascii'));
		}catch(e){
			res.end("Error opening log: "+log.server+'/#'+log.channel+'/'+n+'.log');
		}
	}
}).listen(Settings.port);
server.on("close",function(){
	disp.alert("Ending Log Server");
});
server.on('error',function(e){
	if(e.code == 'EADDRINUSE'){
		setTimeout(function(){
			if(count < Settings.check_timeout){
				count++;
				disp.log("Port "+Settings.port+" in use, reconnect attempt: "+count);
				try{
					server.close();
				}catch(e){}
				server.listen(Settings.port);
			}else{
				count = 0;
				disp.log('Port in use, stopping');
			}
		},Settings.check_interval);
	}else{
		disp.error(e);
	}
});
hook('unload',function(){
	try{
		server.close();
		addZero = null;
	}catch(e){
		disp.alert("Log Server Already Ended");
	}
});
disp.alert("Logging enabled");